package com.zyw.zhuangdian.interceptor;

import com.zyw.zhuangdian.property.MyProperties;
import com.zyw.zhuangdian.service.CacheService;
import com.zyw.zhuangdian.util.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JWTInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private MyProperties properties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行options请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        System.out.println(getIpAddress(request));
        System.out.println(request.getHeaders("User-Agent").nextElement());
        System.out.println("============= path to { "+request.getRequestURI().split("/")[2]+" }============");

        // 获取请求头信息authorization信息
        final String authHeader = request.getHeader(JWTUtil.AUTH_HEADER_KEY);

        if (StringUtils.isNoneEmpty(authHeader) && StringUtils.startsWith(authHeader, properties.getTokenPrefix())) {
            String token = authHeader.replace(properties.getTokenPrefix(), "");
            String uid = JWTUtil.getUserId(token);
            String key = properties.getCacheTokenPrefix() + uid;
            if ("admin".equals(request.getRequestURI().split("/")[2])){
                key = properties.getCacheAdminPrefix() + uid;
            }
            if (cacheService.hasKey(key)) {
                if (cacheService.getKey(key).equals(token)){
                    return true;
                }
            }
        }
        request.getRequestDispatcher("/error?error=401").forward(request, response);
        return false;
    }

    public static String getIpAddress(HttpServletRequest request){
        String ip = request.getHeader("x-forward-for");
        if (StringUtils.isEmpty(ip) || "unknown".equals(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equals(ip)){
            ip = request.getHeader("X-Forwarded-For");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equals(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equals(ip)){
            ip = request.getHeader("X-Real-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equals(ip)){
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)){
            ip = "127.0.0.1";
        }
        return ip;
    }
}
